package com.star.pay.service.impl;

import com.github.wxpay.sdk.WXPay;
import com.star.pay.service.WXPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/*
			  ________   ___   ___        ___   ________   ___   ___        ___
	 ________|\   __  \_|\  \_|\  \______|\  \_|\   __  \_|\  \_|\  \______|\  \_________
	 \       \ \  \_\ /_\ \  \\ \  \     \ \  \\ \  \_\ /_\ \  \\ \  \     \ \  \        \
	  \       \ \   __  \\ \  \\ \  \     \ \  \\ \   __  \\ \  \\ \  \     \ \  \        \
	   \       \ \  \_\  \\ \  \\ \  \____ \ \  \\ \  \_\  \\ \  \\ \  \____ \ \  \        \
	    \       \ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\        \
	     \       \|_______| \|__| \|_______| \|__| \|_______| \|__| \|_______| \|__|         \
	 	  \___________________________________________________________________________________\

*/
@Service
public class WXPayServiceImpl implements WXPayService {

    @Autowired
    private WXPay wxPay;
    @Value("${wxpay.notify_url}")
    private String notify_url;
    /**
     * 支付服务,统一下单接口的调用
     * @param orderId
     * @param money
     * @return
     */
    @Override
    public Map nativePay(String orderId, Integer money) {

        try {

            //1.封装请求参数
            Map map = new HashMap();
            map.put("body","畅购"); //商品描述
            map.put("out_trade_no",orderId); //商户订单号

            //防止精度丢失,设置一分钱
            BigDecimal payMoney = new BigDecimal("0.01");
            BigDecimal fen = payMoney.multiply(new BigDecimal("100")); //1.00
            fen = fen.setScale(0,BigDecimal.ROUND_UP); // 1

            map.put("total_fee",String.valueOf(fen));  //订单总金额，单位 分

            map.put("spbill_create_ip","127.0.0.1");   //终端ip
            map.put("notify_url",notify_url);       //通知地址
            map.put("trade_type", "NATIVE");    //交易类型
            //2.基于WXPay完成同一接口的调用并返回参数
            Map<String, String> result = wxPay.unifiedOrder(map);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 基于微信查询订单
     * @param orderId
     * @return
     */
    @Override
    public Map queryOrder(String orderId) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("out_trade_no", orderId);
            Map<String, String> resultMap = wxPay.orderQuery(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
